<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<script>
		function selectionSort(arr) {
			let { length } = arr
			// length - 1 因为都对比过了剩下的就是最大的
			for (let i = 0; i < length - 1; i++) {
				let minIndex = i
				// j = i 因为最小的都放到前面了,所以前面的不需要循环了
				for (let j = i; j < length; j++) {
					if (arr[j] < arr[minIndex]) {
						minIndex = j
					}
				}
				if (i !== minIndex) {
					swap(arr, i, minIndex)
				}
			}
			console.log(arr);
		}
		selectionSort([1, 5, 3, 5, 8, 4, 99, 2])

		function swap(arr, a, b) {
			let temp = arr[a]
			arr[a] = arr[b]
			arr[b] = temp
		}

	</script>
</body>

</html>